package com.baidu.dao;

import com.baidu.entity.CommentBean;
import com.baidu.entity.NewsBean;
import com.baidu.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.management.Query;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 创作时间：2019/9/23 14:35
 * 作者：李增强
 */
public class NewsDao {
    JDBCUtils ju = new JDBCUtils();
    Connection conn=null;
    public List<NewsBean> getNewsList(String ssql) {
        try {
            conn = ju.getConn();
            String sql="select * from t_news where 1=1 ";
            sql+=ssql;
            QueryRunner ru  =new QueryRunner();
            return ru.query(conn, sql, new BeanListHandler<NewsBean>(NewsBean.class));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public List<CommentBean> getCommentById(String newsid) {
        try {
            conn = ju.getConn();
            String sql="select * from t_comment where newsid="+newsid;
            QueryRunner ru  =new QueryRunner();
            return ru.query(conn, sql, new BeanListHandler<CommentBean>(CommentBean.class));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public Integer getNewsCount(String ssql) {
        try {
            conn = ju.getConn();
            String sql="select count(*) from t_news where 1=1 ";
            sql+=   ssql;
            QueryRunner ru  =new QueryRunner();
            return (int)(long)ru.query(conn, sql, new ScalarHandler<Long>());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public void deleteCommentById(String newsid) throws SQLException {
        String sql="delete from t_comment where newsid="+newsid;
        conn = ju.getConn();
        QueryRunner ru = new QueryRunner();
        ru.update(conn, sql);
    }
    public void deleteNewsById(String newsid) throws SQLException {
        String sql="delete from t_news where id="+newsid;
        conn = ju.getConn();
        QueryRunner ru = new QueryRunner();
        ru.update(conn, sql);
    }

    public void addComment(String newsid, String content, String author, Date createdate) {
        try {
            conn = ju.getConn();
            String sql="insert into t_comment(newsid,content,author,createdate) values(?,?,?,?)";
            QueryRunner ru  =new QueryRunner();
            ru.update(conn, sql,newsid,content,author,createdate);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
    }
}
